import React from 'react';
import cx from 'classnames';
import './styles/index.scss';
// import { getTimeItems } from './utils';
import { getTimeItems } from '@/bases/countdown/utils';
import useIsomorphicLayoutEffect from '@/hooks/useIsomorphicLayoutEffect';
export interface countdownProps {
  /** 倒计时时间,单位毫秒 */
  time: number;
  // 倒计格格式 hh:mm:ss
  format?: string;
  // 结束文案
  endText?: string;
  // 数字样式
  numClassName?: string;
  // 符号样式
  symbolClassName?: string;
  // 结束文案样式
  endTextClassName?: string;
}
const classPrefix = 'ygm-countdown';
// 30小时 ===> 30*60*60*1000=18000000
// format: 'hh:mm:ss'

// [{num:'29',symbol:':'},{num:'59',symbol:':'},{num:'59',symbol:'undefined'}]
// 遍历: '29:59:59'
// 定时器 ===>更新时间===>更新UI
type timeItemType = { num: string; symbol: string }[];
const Countdown: React.FC<countdownProps> = (props) => {
  const [timeItems, setTimeItems] = React.useState<timeItemType>([]);
  const [timeEnd, setTimeEnd] = React.useState<boolean>(false);
  const computeTimeRef = React.useRef<number>(props.time);
  const timerRef = React.useRef<number>(0);
  const endTimesMs = React.useMemo(() => Date.now() + computeTimeRef.current, []);
  const setCountdownTimeItems = React.useCallback(() => {
    if (computeTimeRef.current <= 0) {
      setTimeEnd(true);
      clearInterval(timerRef.current);
    }
    const timeItems = getTimeItems(props.format!, computeTimeRef.current);
    setTimeItems(timeItems);
  }, [props.format]);
  const initCountdown = React.useCallback(() => {
    clearInterval(timerRef.current);
    // 获取当前时间;
    const now = Date.now();
    // 获取剩余时间
    computeTimeRef.current = endTimesMs - now;
    timerRef.current = window.setTimeout(() => {
      initCountdown();
    });
    setCountdownTimeItems();
  }, [endTimesMs, setCountdownTimeItems]);
  // 使用useLayoutEffect钩子函数
  useIsomorphicLayoutEffect(() => {
    initCountdown();

    return () => {
      clearTimeout(timerRef.current);
    };
  }, [initCountdown]);
  return (
    <div className={classPrefix}>
      {timeEnd && props.endText ? (
        <div className={props.endTextClassName}>{props.endText}</div>
      ) : (
        timeItems.map((item, index) => (
          <div className={`${classPrefix}-item`} key={index}>
            <div className={cx(`${classPrefix}-item-num`, props.numClassName)}>{item.num}</div>
            <div className={cx(`${classPrefix}-symbol`, props.symbolClassName)}>{item.symbol}</div>
          </div>
        ))
      )}
    </div>
  );
};
Countdown.displayName = 'Countdown';
Countdown.defaultProps = {
  format: 'hh:mm:ss',
};
export default Countdown;
